package cn.meng.base.listener;


import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.meng.base.vo.CanalDataVo;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

/**
 * Canal消息监控消费者
 * @author 万梦辉
 */
@Component
public class CanalClient{

    @Autowired
    ApplicationContext applicationContext;

    /**
     * 监听获取canal数据，需要做sql解析
     * @param data
     */
    @RabbitListener(queues = {"canal-test"})
    public void handleCanalMessage(String data) {
        if(null == data) {
            return;
        }
        JSONObject jsonObject = JSONUtil.parseObj(data);
        String type = (String) jsonObject.get("type");
        String dateBase = (String) jsonObject.get("database");
        String tableName = (String) jsonObject.get("table");
        List<String> pkNames = (List<String>) jsonObject.get("pkNames");
        List<Map<String,Object>> canalData = (List<Map<String, Object>>) jsonObject.get("data");
        List<Map<String,Object>> oldValue = null;
        Object old = jsonObject.get("old");
        if(!"null".equals(old.toString())) {
            oldValue = (List<Map<String, Object>>) jsonObject.get("old");
        }
        if(null != type && !("".equals(type))) {
            CanalDataVo dataVo = new CanalDataVo(dateBase,tableName,type,canalData,oldValue,pkNames);
            //发布Canal监听事件
            applicationContext.publishEvent(new CanalEvent(dataVo));
        }
    }

}
